﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using br.com.SistemaChamados;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Model;
using br.com.SistemaChamados.Enum;
using br.com.SistemaChamados.Constants;
using System.Web.Security;
using br.com.SistemaChamados.Controller.Common;
using br.com.SistemaChamados.Util;


public partial class Pages_City_UpdateCity : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        ViewStateUserKey = Session.SessionID;
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        br.com.SistemaChamados.Model.Common.User loggedUser = new br.com.SistemaChamados.Model.Common.User();
        UserController userController = new UserController();
        if (Session[UserConstants.SESSION_USER_LOGGED_IN] != null)
        {
            loggedUser.Id = Convert.ToInt32(Session[UserConstants.SESSION_USER_LOGGED_IN]);
            loggedUser = userController.GetUser(loggedUser);
            this.MasterPageFile = MasterPageDefiner.defineMasterPageByAccessRole(loggedUser.Profile);
            ((Label)Master.FindControl("lblUser")).Text = loggedUser.Name;
            this.Title = "SysCall - Sistema de chamados [logado como " + loggedUser.Name + "]";
        }
        else
        {
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (User.IsInRole("ADMIN"))
        {
            if (!IsPostBack)
            {
                FillDdl();
                FillData();
            }
        }
        else
        {
            FormsAuthentication.SignOut();
            Response.Clear();
            Response.Redirect("~/Pages/Login/Login.aspx");
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            City city = new City();
            CityController cityController = new CityController();
            State state = new State();
            state.Id = Convert.ToInt32(ddlState.SelectedValue);
            string id = Session[CityConstants.SESSION_CITY_ID].ToString();
            city.Id = Convert.ToInt32(id);
            city.Description = Convert.ToString(txbCity.Text);
            city.State = state;
            EnumCRUDState resultInsertOperation = cityController.updateCity(city);
            if (resultInsertOperation == EnumCRUDState.SQL_SUCCESS)
            {
                Response.Write(@"<script language='javascript'>alert('Cidade alterada com sucesso!');</script>");
                Response.Redirect("CityMain.aspx"); 
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante a atualização, por favor tente novamente!');</script>");
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro ao atualizar: <br>" + ex.Message + ".');</script>");
            throw ex;
        }
        finally
        {
            Session.Remove("CityIdToUpdate");
        }
    }

    private void FillDdl()
    {
        StateController stateController = new StateController();
        ddlState.DataSource = stateController.GetStates();
        ddlState.DataTextField = "Acronym";
        ddlState.DataValueField = "Id";
        ddlState.DataBind();
        ddlState.Items.Insert(0, "Selecione");
    }

    private void FillData()
    {
        string id = Session[CityConstants.SESSION_CITY_ID].ToString();
        City city = new City();
        city.Id = Convert.ToInt32(id);
        CityController cityController = new CityController();
        try
        {
            city = cityController.SelectCity(city);
            if (city != null)
            {
                txbCity.Text = city.Description.Trim();
            }
            extractStateAndSelectInDropDownList(city);
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro no carregamento dos estados: <br>" + ex.Message +
                               ".');</script>");
        }            
    }

    private void extractStateAndSelectInDropDownList(City city)
    {
        ListItem list = ddlState.Items.FindByValue(Convert.ToString(city.State.Id));
        for (int i = 0; i < ddlState.Items.Count; i++)
        {
            ddlState.Items[i].Selected = false;
        }
        if (list != null)
        {
            list.Selected = true;
        }
        else
        {
            ddlState.Items[0].Selected = true;
        }
    }
}